package com.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Query;

import com.bean.OrderCreate;
import com.bean.OrderSave;
import com.bean.SongCreate;
import com.bean.SongSave;
import com.bean.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.org.apache.xml.internal.serializer.ToUnknownStream;
import com.utils.ChgEcod;
import com.utils.HibCommons;
import com.utils.RenameImg;

public class AdminSongAction extends ActionSupport {
	final static String PATH = ServletActionContext.getServletContext().getRealPath("/");
	private SongCreate songcreate = new SongCreate();
	private List<SongCreate> songcreatelist;
	private SongSave songsave = new SongSave();
	private List<SongSave> songsavelist;
	private List<File> song_add;
	private List<String> song_addFileName;
	private List<String> truepath;
	private String[] name = new String[2];
	private String[] ext = new String[2];
	private User user = new User();
	
	
	/* SongCreate分页方法 */
	private int pageNum_sc;// 当前页
	private int totalpage_sc;// 总页数
	private int pageSize_sc = 3;// 每页条目数
	private int Amount_sc;// 总条目数

	/* SongSave分页方法 */
	private int pageNum_ss;// 当前页
	private int totalpage_ss;// 总页数
	private int pageSize_ss = 3;// 每页条目数
	private int Amount_ss;// 总条目数

	public String querySongCreate() throws Exception {
		/* 接收参数：当前用户名username,用户名头像image,要进入的歌单id */
		HttpServletRequest request = ServletActionContext.getRequest();
		String username = ChgEcod.change(request.getParameter("username"));
		String image = request.getParameter("image");
		String OrderCreateId = request.getParameter("orderId");
		String OrderCreateTitle = ChgEcod.change(request.getParameter("ordertitle"));

		/* 须加分页功能 */
		Amount_sc = getAmount_sc(OrderCreateId, username);
		this.totalpage_sc = Amount_sc % pageSize_sc == 0 ? (Amount_sc / pageSize_sc) : (Amount_sc / pageSize_sc + 1);
		if (pageNum_sc <= 0)
			this.pageNum_sc = 1;
		if (pageNum_sc > totalpage_sc)
			this.pageNum_sc = totalpage_sc;

		/* 根据username和OrderCreateid查询该歌单里的歌曲，所以是从SongCreate表查询 */
		HibCommons.OpenQuery();
		String hql = "From SongCreate sc WHERE sc.b_order = :OrderCreateId" + " AND sc.song_creater = :username";
		Query query = HibCommons.getSession().createQuery(hql);
		query.setParameter("OrderCreateId", OrderCreateId);
		query.setParameter("username", username);
		query.setFirstResult(((pageNum_sc - 1) * pageSize_sc));
		query.setMaxResults(pageSize_sc);

		songcreatelist = query.list();
		HibCommons.CloseQuery();

		User toSongCreateUser = new User();
		toSongCreateUser.setUsername(username);
		toSongCreateUser.setImage(image);

		OrderCreate toSongCreateOrder = new OrderCreate();
		toSongCreateOrder.setOrder_title(OrderCreateTitle);
		toSongCreateOrder.setId(OrderCreateId);

		Map map = ActionContext.getContext().getSession();
		map.put("username", toSongCreateUser);
		map.put("createorder", toSongCreateOrder);

		return SUCCESS;
	}

	public String querySongSave() throws Exception {
		/* 须加分页功能 */
		/*
		 * 进入收藏歌单，须传参数：当前用户名username, 用户名头像image, 要进入的歌单id, 要进入的歌单ordertitle
		 */
		HttpServletRequest request = ServletActionContext.getRequest();
		String username = ChgEcod.change(request.getParameter("username"));
		String image = request.getParameter("image");
		String OrderSaveId = request.getParameter("orderId");
		String OrderSaveTitle = ChgEcod.change(request.getParameter("ordertitle"));
		String fromuser = ChgEcod.change(request.getParameter("fromuser"));
		
		/* 须加分页功能 */
		Amount_ss = getAmount_ss(OrderSaveId, fromuser);
		this.totalpage_ss = Amount_ss % pageSize_ss == 0 ? (Amount_ss / pageSize_ss) : (Amount_ss / pageSize_ss + 1);
		if (pageNum_ss <= 0)
			this.pageNum_ss = 1;
		if (pageNum_ss > totalpage_ss)
			this.pageNum_ss = totalpage_ss;

		/* 根据username和OrderCreateid查询该歌单里的歌曲，所以是从SongCreate表查询 */
		HibCommons.OpenQuery();
		String hql = "From SongCreate ss WHERE ss.b_order = :OrderSaveId" + " AND ss.song_creater = :username";
		Query query = HibCommons.getSession().createQuery(hql);
		query.setParameter("OrderSaveId", OrderSaveId);
		query.setParameter("username", fromuser);
		query.setFirstResult(((pageNum_ss - 1) * pageSize_ss));
		query.setMaxResults(pageSize_ss);

		songcreatelist = query.list();
		HibCommons.CloseQuery();

		User toSongSaveuser = new User();
		toSongSaveuser.setUsername(username);
		toSongSaveuser.setImage(image);

		OrderSave ordersave = new OrderSave();
		ordersave.setOrder_title(OrderSaveTitle);
		ordersave.setId(OrderSaveId);

		Map map = ActionContext.getContext().getSession();
		map.put("username", toSongSaveuser);
		map.put("saveorder", ordersave);

		return SUCCESS;
	}

	public String delSongSave() throws Exception {
		/*
		 * 删除歌单内歌曲，删除成功后，以chain方式返回querySongSave。 须传参数：当前用户名username,
		 * 用户名头像image, 要删除的歌单orderId, 要删除歌曲的delSongId, 要删除的歌单ordertitle
		 */
		HttpServletRequest request = ServletActionContext.getRequest();
		String username = ChgEcod.change(request.getParameter("username"));
		String image = request.getParameter("image");
		String orderId = request.getParameter("orderId");
		String delSongId = request.getParameter("delSongId");
		String ordertitle = ChgEcod.change(request.getParameter("ordertitle"));

		HibCommons.OpenQuery();
		String hql = "DELETE FROM SongSave ss WHERE ss.id = :delSongId";
		Query query = HibCommons.getSession().createQuery(hql);
		query.setParameter("delSongId", delSongId);
		query.executeUpdate();
		HibCommons.CloseQuery();

		Map map = ActionContext.getContext().getSession();
		User toquerySongSaveUser = new User();
		toquerySongSaveUser.setUsername(username);
		toquerySongSaveUser.setImage(image);

		OrderSave toquerySongSaveOrder = new OrderSave();
		toquerySongSaveOrder.setOrder_title(ordertitle);
		toquerySongSaveOrder.setId(orderId);

		map.put("username", toquerySongSaveUser);
		map.put("saveorder", toquerySongSaveOrder);

		return SUCCESS;
	}

	public String delSongCreate() throws Exception {
		/*
		 * 删除歌单内歌曲，删除成功后，以chain方式返回querySongCreate。 须传参数：当前用户名username,
		 * 用户名头像image, 要删除的歌单orderId, 要删除歌曲的delSongId, 要删除的歌单ordertitle
		 */
		HttpServletRequest request = ServletActionContext.getRequest();
		String username = ChgEcod.change(request.getParameter("username"));
		String image = request.getParameter("image");
		String orderId = request.getParameter("orderId");
		String delSongId = request.getParameter("delSongId");
		String ordertitle = ChgEcod.change(request.getParameter("ordertitle"));

		HibCommons.OpenQuery();
		String hql = "DELETE FROM SongCreate sc WHERE sc.id = :delSongId";
		Query query = HibCommons.getSession().createQuery(hql);
		query.setParameter("delSongId", delSongId);
		query.executeUpdate();
		HibCommons.CloseQuery();

		Map map = ActionContext.getContext().getSession();
		User toquerySongCreateUser = new User();
		toquerySongCreateUser.setUsername(username);
		toquerySongCreateUser.setImage(image);
		OrderCreate toquerySongCreateOrder = new OrderCreate();
		toquerySongCreateOrder.setOrder_title(ordertitle);
		toquerySongCreateOrder.setId(orderId);

		map.put("username", toquerySongCreateUser);
		map.put("createorder", toquerySongCreateOrder);

		return SUCCESS;
	}

	public String addSongCreate() throws Exception{
		System.out.println("add song...");
		/* 文件上传 */
		if(song_add != null){
			for(int i = 0;i < song_add.size();i++){
				InputStream is = new FileInputStream(song_add.get(i));
				name[i] = RenameImg.getNewName(getSong_addFileName().get(i));
				OutputStream os = new FileOutputStream(PATH + "img/" + name[i]);
				byte buffer[] = new byte[1024];
				int count = 0;
				while((count = is.read(buffer)) > 0){
					os.write(buffer, 0, count);
				}
				os.close();
				is.close();
				
			}
		}

		/* 获取当前登录用户的用户名 */
		HttpServletRequest request = ServletActionContext.getRequest();
		String username = request.getParameter("username");
		String image = request.getParameter("image");

		/* 获取表单数据 */
		String title = songcreate.getTitle();
		String singer = songcreate.getSinger();
		String cd = songcreate.getCd();
		String b_order = songcreate.getB_order();
		System.out.println(b_order);
		
		
		/* 新建表单局部变量，赋值，封面图片名称为文件上传里得到的，时间为系统自动生成 */
		SongCreate song_add = new SongCreate();
		song_add.setTitle(title);
		song_add.setSinger(singer);
		song_add.setCd(cd);
		song_add.setLim("1");
		song_add.setB_order(b_order);
		song_add.setSong_creater(username);
		song_add.setImg(name[0]);
		song_add.setPlayurl(name[1]);
		
		/* 开启数据库查询事务 */
		HibCommons.OpenQuery();

		/* 写入数据 */
		HibCommons.getSession().save(song_add);

		/* 关闭数据库事务 */
		HibCommons.CloseQuery();

		/* 将用户名写入session */
		Map map = ActionContext.getContext().getSession();
		user.setUsername(username);
		user.setImage(image);
		map.put("username", user);

		return SUCCESS;
	}
	
	public SongCreate getSongcreate() {
		return songcreate;
	}

	public void setSongcreate(SongCreate songcreate) {
		this.songcreate = songcreate;
	}

	public List<SongCreate> getSongcreatelist() {
		return songcreatelist;
	}

	public void setSongcreatelist(List<SongCreate> songcreatelist) {
		this.songcreatelist = songcreatelist;
	}

	public SongSave getSongsave() {
		return songsave;
	}

	public void setSongsave(SongSave songsave) {
		this.songsave = songsave;
	}

	public List<SongSave> getSongsavelist() {
		return songsavelist;
	}

	public void setSongsavelist(List<SongSave> songsavelist) {
		this.songsavelist = songsavelist;
	}

	public int getPageNum_sc() {
		return pageNum_sc;
	}

	public void setPageNum_sc(int pageNum_sc) {
		this.pageNum_sc = pageNum_sc;
	}

	public int getTotalpage_sc() {
		return totalpage_sc;
	}

	public void setTotalpage_sc(int totalpage_sc) {
		this.totalpage_sc = totalpage_sc;
	}

	public int getPageSize_sc() {
		return pageSize_sc;
	}

	public void setPageSize_sc(int pageSize_sc) {
		this.pageSize_sc = pageSize_sc;
	}

	public int getAmount_sc(String OrderCreateId, String username) {
		int i = 0;
		HibCommons.OpenQuery();
		String hql = "SELECT count(*) From SongCreate WHERE b_order = :OrderCreateId"
				+ " AND song_creater = :username";
		Query query = HibCommons.getSession().createQuery(hql);
		query.setParameter("OrderCreateId", OrderCreateId);
		query.setParameter("username", username);
		// 2、获取结果（结果为long类型）
		Object obj = query.uniqueResult();
		// 3、转化为long(类型为long，转为int会报错)
		Long long1 = (Long) obj;
		i = long1.intValue();
		HibCommons.CloseQuery();
		
		System.out.println("i:"+i);
		return i;
	}

	public void setAmount_sc(int amount_sc) {
		Amount_sc = amount_sc;
	}

	public int getPageNum_ss() {
		return pageNum_ss;
	}

	public void setPageNum_ss(int pageNum_ss) {
		this.pageNum_ss = pageNum_ss;
	}

	public int getTotalpage_ss() {
		return totalpage_ss;
	}

	public void setTotalpage_ss(int totalpage_ss) {
		this.totalpage_ss = totalpage_ss;
	}

	public int getPageSize_ss() {
		return pageSize_ss;
	}

	public void setPageSize_ss(int pageSize_ss) {
		this.pageSize_ss = pageSize_ss;
	}

	public int getAmount_ss(String OrderSaveId, String username) {
		int i = 0;
		HibCommons.OpenQuery();
		String hql = "SELECT count(*) From SongCreate ss WHERE ss.b_order = :OrderSaveId" + " AND ss.song_creater = :username";
		Query query = HibCommons.getSession().createQuery(hql);
		query.setParameter("OrderSaveId", OrderSaveId);
		query.setParameter("username", username);
		// 2、获取结果（结果为long类型）
		Object obj = query.uniqueResult();
		// 3、转化为long(类型为long，转为int会报错)
		Long long1 = (Long) obj;
		i = long1.intValue();
		HibCommons.CloseQuery();
		return i;
	}

	public void setAmount_ss(int amount_ss) {
		Amount_ss = amount_ss;
	}

	

	public List<File> getSong_add() {
		return song_add;
	}

	public void setSong_add(List<File> song_add) {
		this.song_add = song_add;
	}

	

	public List<String> getSong_addFileName() {
		return song_addFileName;
	}

	public void setSong_addFileName(List<String> song_addFileName) {
		this.song_addFileName = song_addFileName;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public static String getPath() {
		return PATH;
	}

	public int getAmount_sc() {
		return Amount_sc;
	}

	public int getAmount_ss() {
		return Amount_ss;
	}

	public List<String> getTruepath() {
		return truepath;
	}

	public void setTruepath(List<String> truepath) {
		this.truepath = truepath;
	}

	public String[] getName() {
		return name;
	}

	public void setName(String[] name) {
		this.name = name;
	}

	public String[] getExt() {
		return ext;
	}

	public void setExt(String[] ext) {
		this.ext = ext;
	}
	
	

}
